package tv.huan.media.service.impl;

import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tv.huan.common.core.text.Convert;
import tv.huan.common.exception.BusinessException;
import tv.huan.common.utils.DateUtils;
import tv.huan.common.utils.StringUtils;
import tv.huan.media.domain.*;
import tv.huan.media.mapper.*;
import tv.huan.media.rabbit.RabbitConstant;
import tv.huan.media.service.IAlbumService;
import tv.huan.media.util.MailInfoUtil;
import tv.huan.system.domain.SysUser;
import tv.huan.system.mapper.SysUserMapper;

/**
 * 专辑Service业务层处理
 * 
 * @author admin
 * @date 2019-10-08
 */
@Service
public class AlbumServiceImpl implements IAlbumService 
{
    private static final Logger log = LoggerFactory.getLogger(AlbumServiceImpl.class);

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private ItemAlbumMapper itemAlbumMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ClassificationMapper classificationMapper;

    @Autowired
    private AuthorizerMapper authorizerMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    /**
     * 查询专辑
     * 
     * @param albumId 专辑ID
     * @return 专辑
     */
    @Override
    public Album selectAlbumById(Long albumId)
    {
        return albumMapper.selectAlbumById(albumId);
    }

    /**
     * 查询专辑
     *
     * @param title 专辑title
     * @return 专辑
     */
    public Album selectAlbumByTitle(String title){
        return albumMapper.selectAlbumByTitle(title);
    }

    /**
     * 查询专辑列表
     * 
     * @param album 专辑
     * @return 专辑
     */
    @Override
    public List<Album> selectAlbumList(Album album)
    {
        return albumMapper.selectAlbumList(album);
    }

    /**
     * 新增专辑
     * 
     * @param album 专辑
     * @return 结果
     */
    @Override
    public int insertAlbum(Album album)
    {
        album.setCreateTime(DateUtils.getNowDate());
        return albumMapper.insertAlbum(album);
    }

    /**
     * 修改专辑
     * 
     * @param album 专辑
     * @return 结果
     */
    @Override
    public int updateAlbum(Album album)
    {
        album.setUpdateTime(DateUtils.getNowDate());
        return albumMapper.updateAlbum(album);
    }

    /**
     * 删除专辑对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAlbumByIds(String ids) throws Exception
    {
        Long[] idArr = Convert.toLongArray(ids);
        ItemAlbum itemAlbum = new ItemAlbum();
        int count;
        for (Long id : idArr){
            itemAlbum.setAlbumId(id);
            count = this.itemAlbumMapper.getItemOrAlbumUseingCountById(itemAlbum);
            if (count > 0){
                throw new Exception("专辑使用中，无法删除");
            }
        }
        return albumMapper.deleteAlbumByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除专辑信息
     * 
     * @param albumId 专辑ID
     * @return 结果
     */
    public int deleteAlbumById(Long albumId)
    {
        return albumMapper.deleteAlbumById(albumId);
    }


    /**
     * 导入专辑
     *
     * @param albumList 专辑集合
     * @param updateSupport 是否更新已存在的专辑
     * @return 结果
     */
    @Override
    public String importAlbum(List<Album> albumList, boolean updateSupport) {
        if (StringUtils.isNull(albumList) || albumList.size() == 0)
        {
            throw new BusinessException("导入专辑数据不能为空！");
        }
        Date now = DateUtils.getNowDate();
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Album album : albumList)
        {
            try
            {
                if (StringUtils.isEmpty(album.getTitle())){
                    throw new Exception("名称为空！");
                }else if (null == album.getClassId()){
                    throw new Exception("分类ID为空！");
                }else if (null ==album.getAuthorizerId() ){
                    throw new Exception("授权方ID为空！");
                }else if (StringUtils.isEmpty(album.getEpisodeAll())){
                    throw new Exception("总集数为空！");
                }else if (StringUtils.isEmpty(album.getAuthorBeginDate()) || StringUtils.isEmpty(album.getAuthorEndDate())){
                    throw new Exception("授权开始或者授权结束日期为空！");
                }else if (StringUtils.isEmpty(album.getContentLevel())){
                    throw new Exception("内容等级为空！");
                }else if (null == album.getPurchaseType()){
                    throw new Exception("采购类型为空！");
                }
                //验证是否存在分类
                Classification c = classificationMapper.selectClassificationById(album.getClassId());
                if (null == c){
                    throw new Exception("分类id不存在！");
                }
                //验证是否存在授权方
                Authorizer au = authorizerMapper.selectAuthorizerById(album.getAuthorizerId());
                if (null == au){
                    throw new Exception("授权方id不存在！");
                }
                // 验证是否存在这个专辑
                Album a = albumMapper.selectAlbumByTitle(album.getTitle());
                if (StringUtils.isNull(a))
                {
                    album.setCreateTime(now);
                    this.insertAlbum(album);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、专辑 " + album.getTitle() + " 导入成功");
                }
                else if (updateSupport)
                {
                    album.setAlbumId(a.getAlbumId());
                    this.updateAlbum(album);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、专辑 " + album.getTitle() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、专辑 " + album.getTitle() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、专辑 " + album.getTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0 && successNum == 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else if (failureNum > 0 && successNum > 0)
        {
            failureMsg.insert(0, "部分导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return  successMsg.toString();
    }

    /**
     * 推荐
     *
     * @param albumIds 专辑id
     * @param itemIds  项目id
     * @return 结果
     */
    @Override
    @Transactional
    public void recommend(String albumIds, String itemIds,  SysUser user) throws Exception{
        Long[] albumIdArr = Convert.toLongArray(albumIds);
        Long[] itemIdArr = Convert.toLongArray(itemIds);
        ItemAlbum ia;
        Date nowDate = DateUtils.getNowDate();
        StringBuilder itemNames = new StringBuilder("");
        Item item;
        for (long itemId : itemIdArr){
            if (!itemNames.toString().equals("")){
                itemNames.append("、");
            }
            item = itemMapper.selectItemById(itemId);
            itemNames.append(item.getName());
            for (long albumId : albumIdArr){
                ia = new ItemAlbum();
                ia.setAlbumId(albumId);
                ia.setItemId(itemId);
                ia.setCreateTime(nowDate);
                ia.setCreateBy(user.getUserName());
                this.itemAlbumMapper.insertItemAlbum(ia);
            }
        }
        String[] ids = albumIds.split(",");
        List<Album> albumList = albumMapper.selectAlbumListByIds(ids);

        String subject = "推荐上线";
        String text = "<h5>请注意：" +
                "<br />\n" +
                "以下内容推荐在 [" + itemNames + "] 上线，请查收！" +
                "<br />\n" +
                "<br/>推荐片单如下：\n</h5>";
        String jsonParam = MailInfoUtil.getRequestJsonParam(subject,text,MailInfoUtil.RECOMEND,albumList);
        rabbitmqTemplate.convertAndSend(RabbitConstant.DIRECT_EMAIL_EXCHANGE,RabbitConstant.EMAIL_ROUTING,jsonParam);
    }

    /**
     * 下线通知
     *
     * @param ids 专辑ids
     * @param offLineReason 原因
     * @return 结果
     */
    public void offLineNotice(String ids, String offLineReason) throws Exception{
        List<SysUser> users = userMapper.selectUserList(new SysUser());
        StringBuilder sb = new StringBuilder("");
        for (SysUser user : users){
            if (StringUtils.isNotEmpty(user.getEmail())){
                sb.append(user.getEmail() + ",");
            }
        }
        String[] idArr = ids.split(",");
        List<Album> albumList = albumMapper.selectAlbumListByIds(idArr);
        String subject = "下线通知";
        String text = "<h5>请注意：" +
                "<br />\n" +
                "以下内容因 [" + offLineReason + "] 需要下线，请查收！" +
                "<br />\n" +
                "<br/>需下线片单如下：\n</h5>";
        String jsonParam = MailInfoUtil.getRequestJsonParam(subject,text,MailInfoUtil.OFF_LINE_NOTIFY,albumList);
        rabbitmqTemplate.convertAndSend(RabbitConstant.DIRECT_EMAIL_EXCHANGE,RabbitConstant.EMAIL_ROUTING,jsonParam);
    }
}
